import "./index.css"
let arr = [
  { id: 1, name: "iPhone 15", price: 5999 },
  { id: 2, name: "iPhone 15 Pro", price: 7999 },
  { id: 3, name: "iPhone 15 Pro Max", price: 8999 },
];
// 输入模块
(function () {
  let newId = document.querySelector(".id");
  let newName = document.querySelector(".name");
  let newPrice = document.querySelector(".price");
  let newSubmit = document.querySelector(".submit");
  newSubmit.addEventListener("click", function (e) {
    if (newId.value && newName.value && newPrice.value) {
      e.preventDefault();
      let id = Number(newId.value);
      let name = newName.value;
      let price = Number(newPrice.value);
      if (isNaN(id)) {
        alert("请输入正确的id");
        newId.value = null;
        newName.value = null;
        newPrice.value = null;
        return;
      } else if (isNaN(price)) {
        alert("请输入正确的价钱");
        newId.value = null;
        newName.value = null;
        newPrice.value = null;
        return;
      }
      let newObj = {};
      newObj["id"] = id;
      newObj["name"] = name;
      newObj["price"] = price;
      arr.push(newObj);
      console.log(arr);
    } else {
      alert("请输入完整信息");
    }
    newId.value = null;
    newName.value = null;
    newPrice.value = null;
  });
})();

//渲染函数
(function () {
  const box = document.querySelector(".box");
  const btn = document.querySelector("button");
  btn.addEventListener("click", function () {
    // 先判断该表格是否存在存在就删除
    let preTable = document.querySelector("table");
    if (preTable) {
      preTable.remove();
    }

    let table = document.createElement("table");
    let thead = document.createElement("thead");
    let tbody = document.createElement("tbody");
    box.appendChild(table);
    table.appendChild(thead);
    table.appendChild(tbody);
    //获取对象的属性个数,直接去第一个（后期再加数组空的情况）
    let typeLength = Object.keys(arr[0]).length;
    // 定义表头属性值(数组形式)
    let thName = Object.keys(arr[0]);
    // 添加表头
    let thTr = document.createElement("tr");
    thead.appendChild(thTr);
    for (let i = 0; i < typeLength; i++) {
      let th = document.createElement("th");
      // 获取表头属性值
      th.appendChild(document.createTextNode(`${thName[i]}`));
      thTr.appendChild(th);
    }
    // 添加单元格行
    for (let i = 0; i < arr.length; i++) {
      let tbTr = document.createElement("tr");
      tbody.appendChild(tbTr);
      for (let j = 0; j < typeLength; j++) {
        let td = document.createElement("td");
        // 获取values
        let values = Object.values(arr[i]);
        // 获取表头属性值
        td.appendChild(document.createTextNode(`${values[j]}`));
        tbTr.appendChild(td);
      }
    }
  });
})();